﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using System.Runtime.InteropServices;
using System.Globalization;
using System.DirectoryServices;
using System.DirectoryServices.AccountManagement;

using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Taxonomy;
using Microsoft.Office.Server.UserProfiles;

namespace JobUsersSync2.Features.JobUsersSync2
{
    [Guid("EA72641D-8080-4A4D-99D1-DBF9C88DCAE2")]
    public class JobUsersSync2 : SPJobDefinition
    {
        #region Propertys
        private string _DisplayName =
@"(Ko) Job Users Profiles Sync 2, ver. 1.0.0.5";
        public override string DisplayName
        {
            get
            {
                return _DisplayName;
            }
        }
        private string _Description =
@"(Ko) Job Users Profiles Sync 2, ver. 1.0.0.5";
        public override string Description
        {
            get
            {
                return _Description;
            }
        }
        #endregion Propertys
        #region Members
        #endregion Members
        #region Constructors
        public JobUsersSync2() : base()
        {
            this.Title = "(Ko) Job Users Profiles Sync 2";
        }
        public JobUsersSync2(string jobName, SPService service, SPServer server, SPJobLockType targetType)
            : base(jobName, service, server, targetType)
        {
            this.Title = "(Ko) Job Users Profiles Sync 2";
        }
        public JobUsersSync2(string jobName, SPWebApplication webApplication)
            : base(jobName, webApplication, null, SPJobLockType.ContentDatabase)
        {
            this.Title = "(Ko) Job Users Profiles Sync 2";
        }
        #endregion Constructors
        #region Common Methods
        public string AllTrim(String mStr)
        {
            String vStr = mStr.Replace(" ", string.Empty);
            return vStr;
        }
        public string ConverDate(String mDate)
        {
            String vDate = "";
            //--
            int mCMP = 0;
            if ((mCMP = mDate.IndexOf(".")) != -1)
            {
                vDate = mDate.Substring(6, 4) + "-" + mDate.Substring(3, 2) + "-" + mDate.Substring(0, 2);
            }
            else
            {
                vDate = mDate;
            }
            //--
            return vDate;
        }
        public string InValue(object mValue)
        {
            String mStr;
            if (mValue == null)
                mStr = "";
            else
                mStr = mValue.ToString();
            return mStr;
        }
        #endregion Common Methods
        #region Data Methods
        public Exception GetDateBirth(ref string parRet, string ID1C)
        {
            return DB1CUser.GetDateBirth(ref parRet, ID1C);
        }
        public Exception GetDateArb(ref string parRet, string ID1C)
        {
            return DB1CUser.GetDateArb(ref parRet, ID1C);
        }
        #endregion Data Methods

        #region Job Methods
        public Exception Execute(Guid contentDbId, string siteStr)
        {
            Exception ret = null;
            CreateOfficeUser(siteStr);
            CreateShopsUser(siteStr);
            return ret;
        }
        public override void Execute(Guid contentDbId)
        {
            Exception err = Execute(contentDbId, "http://localhost");
        }
        #endregion Job Methods
        #region Process Methods
        public Exception CreateOfficeUser(string siteStr)
        {
            #region Members
            Exception err = null;
            int Count = 0;
            String mOfficeName =
                KoEnvironment.GetAppSetting(@"ADOffice");
            DirectorySearcher search =
                new DirectorySearcher(
                    new DirectoryEntry(
                        KoEnvironment.GetAppSetting("ADServer")
                            , KoEnvironment.GetAppSetting("ADUser")
                            , KoEnvironment.GetAppSetting("ADPass")));
            search.Filter =
                "(&(physicaldeliveryofficename="
                + KoEnvironment.GetAppSetting("ADOffice") + "))";
            //search.PropertiesToLoad.Add(propertyName);
            SearchResultCollection results = search.FindAll();
            #endregion Members
            using (SPSite site = new SPSite(siteStr))
            {
                #region Members
                SPServiceContext context = SPServiceContext.GetContext(site);
                UserProfileManager uprofileManager = new UserProfileManager(context);
                UserProfile up;
                #endregion Members
                #region foreach
                foreach (SearchResult result in results)
                {
                    #region Members
                    String DispName = "";
                    String Email = "";
                    String Phone = "";
                    String OfficeName = "";
                    String AccountControl = "";
                    String ID1C = "";
                    String LoginName = "";
                    String JOB = "";
                    String Otdel = "";
                    String Name1 = "";
                    String Name2 = "";
                    String Name3 = "";
                    String BDate = "";
                    string ADate = "";
                    #endregion Members
                    #region Get Properties
                    foreach (string propertName in result.Properties.PropertyNames)
                    {
                        foreach (Object retEntry in result.Properties[propertName])
                        {
                            switch (propertName.ToUpper())
                            {
                                case "SN":
                                    Name1 = retEntry.ToString();
                                    break;

                                case "GIVENNAME":
                                    Name2 = retEntry.ToString();
                                    break;

                                case "EXTENSIONATTRIBUTE3":
                                    Name3 = retEntry.ToString();
                                    break;

                                case "DISPLAYNAME":
                                    DispName = retEntry.ToString();
                                    break;

                                case "PHYSICALDELIVERYOFFICENAME":
                                    OfficeName = retEntry.ToString();
                                    break;

                                case "USERACCOUNTCONTROL":
                                    AccountControl = retEntry.ToString();
                                    break;

                                case "EXTENSIONATTRIBUTE4":
                                    ID1C = retEntry.ToString();
                                    break;

                                case "SAMACCOUNTNAME":
                                    LoginName = retEntry.ToString();
                                    break;

                                case "MAIL":
                                    Email = retEntry.ToString();
                                    break;

                                case "TELEPHONENUMBER":
                                    Phone = retEntry.ToString();
                                    break;

                                case "DEPARTMENT":
                                    Otdel = retEntry.ToString();
                                    break;

                                case "TITLE":
                                    JOB = retEntry.ToString();
                                    break;
                            }
                        }
                    }
                    #endregion Get Properties
                    String sAccount = KoEnvironment.GetAppSetting("DomainName") + "\\" + LoginName;
                    #region BDate and DateArb
                    err = GetDateBirth(ref BDate, ID1C);
                    if (err != null)
                        break;
                    err = GetDateArb(ref ADate, ID1C);
                    if (err != null)
                        break;
                    #endregion BDate and DateArb
                    if (OfficeName == mOfficeName && (AccountControl == "512" || AccountControl == "66048"))
                    {
                        if (Count < 50000)
                        {
                            String mStrLog = "";
                            int Change = 0;
                            try
                            {
                                #region Get User Profile or new SPUser
                                if (uprofileManager.UserExists(sAccount))
                                {
                                    up = uprofileManager.GetUserProfile(sAccount);
                                    mStrLog += "Edit User: " + LoginName;
                                }
                                else
                                {
                                    up = uprofileManager.CreateUserProfile(sAccount);
                                    mStrLog += "Add User: " + LoginName;
                                }
                                #endregion Get User Profile
                                #region WorkPhone and WorkEmail and ID1C
                                if (InValue(up["WorkPhone"].Value).Trim() != Phone.Trim())
                                {
                                    up["WorkPhone"].Value = Phone;
                                    mStrLog += " WorkPhone " + Phone;
                                    Change++;
                                }
                                if (InValue(up["WorkEmail"].Value).Trim() != Email.Trim())
                                {
                                    up["WorkEmail"].Value = Email;
                                    mStrLog += " WorkEmail " + Email;
                                    Change++;
                                }
                                if (InValue(up["ID1C"].Value).Trim() != ID1C.Trim())
                                {
                                    up["ID1C"].Value = ID1C;
                                    mStrLog += " ID1C " + ID1C + " OLD ID1C: " + InValue(up["ID1C"].Value);
                                    Change++;
                                }
                                #endregion WorkPhone and WorkEmail and ID1C
                                #region ReMake Photo
                                //if (File.Exists(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\photo\" + ID1C.Trim() + ".jpg"))
                                //{
                                //    if (InValue(up["PictureUrl"].Value).Trim() != sUrl + "/_layouts/photo/" + ID1C.Trim() + ".jpg")
                                //    {
                                //        up["PictureUrl"].Value = sUrl + "/_layouts/photo/" + ID1C.Trim() + ".jpg";
                                //        //mStrLog += " Foto " + sUrl + "/_layouts/photo/" + ID1C.Trim() + ".jpg";
                                //        Change++;
                                //    }
                                //}
                                #endregion ReMake Photo
                                #region Office, Department, SPS-JobTitle, Title, FirstName, LastName, SPS-PhoneticDisplayName, PreferredName
                                if (InValue(up["Office"].Value).Trim() != OfficeName.Trim())
                                {
                                    up["Office"].Value = OfficeName;
                                    mStrLog += " Office " + OfficeName;
                                    Change++;
                                }
                                if (InValue(up["Department"].Value).Trim() != Otdel.Trim())
                                {
                                    up["Department"].Value = Otdel;
                                    mStrLog += " Department " + Otdel;
                                    Change++;
                                }
                                if (AllTrim(InValue(up["SPS-JobTitle"].Value)) != AllTrim(JOB))
                                {
                                    String mOld = InValue(up["SPS-JobTitle"].Value);
                                    up["SPS-JobTitle"].Value = JOB;
                                    mStrLog += " SPS-JobTitle " + JOB + " SPS-JobTitle(Old) " + mOld;
                                    Change++;
                                }
                                if (InValue(up["Title"].Value).Trim() != JOB.Trim())
                                {
                                    up["Title"].Value = JOB;
                                    mStrLog += " Title " + JOB;
                                    Change++;
                                }
                                if (InValue(up["FirstName"].Value).Trim() != Name2.Trim())
                                {
                                    up["FirstName"].Value = Name2;
                                    mStrLog += " FirstName " + Name2;
                                    Change++;
                                }
                                if (InValue(up["LastName"].Value).Trim() != Name1.Trim())
                                {
                                    up["LastName"].Value = Name1;
                                    mStrLog += " LastName " + Name1;
                                    Change++;
                                }
                                if (InValue(up["SPS-PhoneticDisplayName"].Value) != "")
                                {
                                    up["SPS-PhoneticDisplayName"].Value = "";
                                    mStrLog += " SPS-PhoneticDisplayName = '' ";
                                    Change++;
                                }
                                if (InValue(up["PreferredName"].Value).Trim() != (Name1 + " " + Name2 + " " + Name3).Trim())
                                {
                                    up["PreferredName"].Value = Name1 + " " + Name2 + " " + Name3;
                                    mStrLog += " PreferredName " + Name1 + " " + Name2 + " " + Name3;
                                    Change++;
                                }
                                #endregion
                                #region ADate, BDate
                                if (
                                    ADate != "" 
                                    && ConverDate(InValue(up["SPS-HireDate"].Value)).Trim() != ADate.Trim())
                                {
                                    up["SPS-HireDate"].Value = ADate;
                                    mStrLog += " SPS-HireDate " + ADate;
                                    Change++;
                                }
                                if (
                                    BDate != "" 
                                    && ConverDate(InValue(up["SPS-Birthday"].Value)) != BDate)
                                {
                                    up["SPS-Birthday"].Value = BDate;
                                    mStrLog += " SPS-Birthday " + BDate;
                                    Change++;
                                }
                                #endregion ADate, BDate
                                #region Photo
                                /* 
                                if (InValue(up["PictureURL"].Value) != ttt)
                                {
                                    up["PictureURL"].Value = ttt;
                                    CreateLineLog(contentDbId, "Change User " + LoginName + " PictureURL " + ttt);
                                    Change++;
                                }
                                */
                                #endregion Photo
                                #region Save changes
                                if (Change > 0)
                                {
                                    //if (mStrLog.Length > 40)
                                    //    CreateLineLog(mStrLog);
                                    up.Commit();
                                }
                                if (up.PersonalSite == null)
                                {
                                    up.CreatePersonalSite();
                                    //CreateLineLog("Add Personal Site User " + LoginName + "url: " + up.PersonalUrl);
                                }
                                #endregion Save changes
                            }
                            catch
                            {
                                // CreateLineLog("Error Code User " + LoginName);
                                err = new Exception("CreateOfficeUser() :: Error Code User :: " + LoginName);
                            }
                        }
                    }
                    else // if (OfficeName == mOfficeName && (AccountControl == "512" || AccountControl == "66048"))
                    {
                        try
                        {
                            if (uprofileManager.UserExists(sAccount))
                            {
                                //uprofileManager.RemoveUserProfile(sAccount);
                            }
                        }
                        catch
                        {
                            // CreateLineLog("Error Code User " + LoginName);
                            err = new Exception("CreateOfficeUser() :: Error Code User :: " + LoginName);
                        }
                    } // if (OfficeName == mOfficeName && (AccountControl == "512" || AccountControl == "66048"))
                    Count++;
                } // foreach (SearchResult result in results)
                #endregion foreach
            } // using (SPSite site = new SPSite(siteStr))
            return err;
        }
        public Exception CreateShopsUser(string siteStr)
        {
            #region Members
            //CreateLineLog("Start Shop Users!");
            Exception err = null;
            int Count = 0;
            String mOfficeName = KoEnvironment.GetAppSetting("ADOffice");
            DirectorySearcher search =
                new DirectorySearcher(
                    new DirectoryEntry(KoEnvironment.GetAppSetting("ADServer")
                        , KoEnvironment.GetAppSetting("ADUser")
                        , KoEnvironment.GetAppSetting("ADPass")));
            //search.Filter = "(!(physicaldeliveryofficename = " + GetValueSetting("ADOffice") + "))";
            search.Filter = "(|(useraccountcontrol=512)(useraccountcontrol=66048))";
            //search.PropertiesToLoad.Add(propertyName);
            SearchResultCollection results = search.FindAll();
            #endregion Members
            #region Foreach
            foreach (SearchResult result in results)
            {
                #region members
                //String DispName = "";
                String Email = "";
                String Phone = "";
                String SHOP = "";
                String AccountControl = "";
                String ID1C = "";
                String LoginName = "";
                String JOB = "";
                //String Otdel = "";
                string OFFICE = "";
                String Name1 = "";
                String Name2 = "";
                String Name3 = "";
                String BDate = "";
                String ADate = "";
                #endregion members
                #region foreach propert
                foreach (string propertName in result.Properties.PropertyNames)
                {
                    foreach (Object retEntry in result.Properties[propertName])
                    {
                        switch (propertName.ToUpper())
                        {
                            case "SN":
                                Name1 = retEntry.ToString();
                                break;
                            case "GIVENNAME":
                                Name2 = retEntry.ToString();
                                break;
                            case "EXTENSIONATTRIBUTE3":
                                Name3 = retEntry.ToString();
                                break;
                            //case "DISPLAYNAME":
                            //    DispName = retEntry.ToString();
                            //    break;
                            case "PHYSICALDELIVERYOFFICENAME":
                                OFFICE = retEntry.ToString();
                                break;
                            case "USERACCOUNTCONTROL":
                                AccountControl = retEntry.ToString();
                                break;
                            case "EXTENSIONATTRIBUTE4":
                                ID1C = retEntry.ToString();
                                break;
                            case "SAMACCOUNTNAME":
                                LoginName = retEntry.ToString();
                                break;
                            case "MAIL":
                                Email = retEntry.ToString();
                                break;
                            case "TELEPHONENUMBER":
                                Phone = retEntry.ToString();
                                break;
                            case "DEPARTMENT":
                                SHOP = retEntry.ToString();
                                break;
                            case "TITLE":
                                JOB = retEntry.ToString();
                                break;
                        } // switch (propertName.ToUpper())
                    } // foreach (Object retEntry in result.Properties[propertName])
                } // foreach (string propertName in result.Properties.PropertyNames)
                #endregion foreach propert
                #region BDate and DateArb
                err = GetDateBirth(ref BDate, ID1C);
                if (err != null)
                    break;
                err = GetDateArb(ref ADate, ID1C);
                if (err != null)
                    break;
                #endregion BDate and DateArb
                if (SHOP == "Разумовская")
                    SHOP = "Петровско Разумовская";
                //--
                //if (AccountControl == "512")
                //CreateLineLog("Start item!!!!!   User: " + Name1 + " Mail: " + Email + " shop: " + OFFICE + " shop1: " + SHOP + " AccountControl " + AccountControl);
                if (
                    Email != "" && Name1 != ""
                    && OFFICE != "Румянцево"
                    && (AccountControl == "512" || AccountControl == "66048"))
                {
                    //CreateLineLog("User: " + Name1 + " Mail: " + Email + " shop: " + OFFICE + " shop1: " + SHOP + " AccountControl " + AccountControl);
                    if (Count < 5000)
                    {
                        //CreateLineLog("User " + LoginName);
                        String mStrLog = "";
                        try
                        {
                            String sAccount = KoEnvironment.GetAppSetting("DomainName") + "\\" + LoginName;
                            using (SPSite site = new SPSite(siteStr))
                            {
                                SPServiceContext context = SPServiceContext.GetContext(site);
                                UserProfileManager uprofileManager = new UserProfileManager(context);
                                UserProfile up;
                                #region Get SP user object
                                if (uprofileManager.UserExists(sAccount))
                                {
                                    up = uprofileManager.GetUserProfile(sAccount);
                                    mStrLog += "Edit User: " + LoginName;
                                }
                                else
                                {
                                    up = uprofileManager.CreateUserProfile(sAccount);
                                    mStrLog += "Add User: " + LoginName;
                                }
                                #endregion
                                int Change = 0;
                                #region WorkPhone, WorkEmail, ID1C
                                if (InValue(up["WorkPhone"].Value).Trim() != Phone.Trim())
                                {
                                    up["WorkPhone"].Value = Phone;
                                    mStrLog += " WorkPhone " + Phone;
                                    Change++;
                                }
                                if (InValue(up["WorkEmail"].Value).Trim() != Email.Trim())
                                {
                                    up["WorkEmail"].Value = Email;
                                    mStrLog += " WorkEmail " + Email;
                                    Change++;
                                }
                                if (InValue(up["ID1C"].Value).Trim() != ID1C.Trim())
                                {
                                    up["ID1C"].Value = ID1C;
                                    mStrLog += " ID1C " + ID1C + " OLD ID1C: " + InValue(up["ID1C"].Value);
                                    Change++;
                                }
                                #endregion WorkPhone, WorkEmail, ID1C
                                #region Photo
                                //if (File.Exists(@"C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\LAYOUTS\photo\" + Email.Trim() + ".jpg"))
                                //{
                                //    if (InValue(up["PictureUrl"].Value).Trim() != sUrl + "/_layouts/photo/" + Email.Trim() + ".jpg")
                                //    {
                                //        up["PictureUrl"].Value = sUrl + "/_layouts/photo/" + Email.Trim() + ".jpg";
                                //        //mStrLog += " Foto " + sUrl + "/_layouts/photo/" + Email.Trim() + ".jpg";
                                //        Change++;
                                //    }
                                //}
                                #endregion Photo
                                #region Office, SPS-JobTitle, Title, FirstName, LastName, etc
                                if (InValue(up["Office"].Value).Trim() != SHOP.Trim())
                                {
                                    up["Office"].Value = SHOP;
                                    mStrLog += " Office " + SHOP;
                                    Change++;
                                }
                                if (AllTrim(InValue(up["SPS-JobTitle"].Value)) != AllTrim(JOB))
                                {
                                    String mOld = InValue(up["SPS-JobTitle"].Value);
                                    up["SPS-JobTitle"].Value = JOB;
                                    mStrLog += " SPS-JobTitle " + JOB + " SPS-JobTitle(Old) " + mOld;
                                    Change++;
                                }
                                if (InValue(up["Title"].Value).Trim() != JOB.Trim())
                                {
                                    up["Title"].Value = JOB;
                                    mStrLog += " Title " + JOB;
                                    Change++;
                                }
                                if (InValue(up["FirstName"].Value).Trim() != Name2.Trim())
                                {
                                    up["FirstName"].Value = Name2;
                                    mStrLog += " FirstName " + Name2;
                                    Change++;
                                }
                                if (InValue(up["LastName"].Value).Trim() != Name1.Trim())
                                {
                                    up["LastName"].Value = Name1;
                                    mStrLog += " LastName " + Name1;
                                    Change++;
                                }
                                if (InValue(up["SPS-PhoneticDisplayName"].Value) != "")
                                {
                                    up["SPS-PhoneticDisplayName"].Value = "";
                                    mStrLog += " SPS-PhoneticDisplayName = '' ";
                                    Change++;
                                }
                                if (InValue(up["PreferredName"].Value).Trim() != (Name1 + " " + Name2 + " " + Name3).Trim())
                                {
                                    up["PreferredName"].Value = Name1 + " " + Name2 + " " + Name3;
                                    mStrLog += " PreferredName " + Name1 + " " + Name2 + " " + Name3;
                                    Change++;
                                }
                                #endregion Office, SPS-JobTitle, Title, FirstName, LastName, etc
                                #region BDate, ADate
                                if (
                                    ADate != "" && 
                                    ConverDate(InValue(up["SPS-HireDate"].Value)).Trim() != ADate.Trim())
                                {
                                    up["SPS-HireDate"].Value = ADate;
                                    mStrLog += " SPS-HireDate " + ADate;
                                    Change++;
                                }
                                if (
                                    BDate != "" && 
                                    ConverDate(InValue(up["SPS-Birthday"].Value)) != BDate)
                                {
                                    up["SPS-Birthday"].Value = BDate;
                                    mStrLog += " SPS-Birthday " + BDate;
                                    Change++;
                                }
                                #endregion BDate, ADate
                                #region Photo
                                /* 
                                if (InValue(up["PictureURL"].Value) != ttt)
                                {
                                    up["PictureURL"].Value = ttt;
                                    CreateLineLog(contentDbId, "Change User " + LoginName + " PictureURL " + ttt);
                                    Change++;
                                }
                                */
                                #endregion Photo
                                #region Save change
                                if (Change > 0)
                                {
                                    //if (mStrLog.Length > 40)
                                    //    CreateLineLog(mStrLog);
                                    up.Commit();
                                }
                                if (up.PersonalSite == null)
                                {
                                    up.CreatePersonalSite();
                                    //CreateLineLog("Add Personal Site User " + LoginName + "url: " + up.PersonalUrl);
                                }
                                #endregion Save change
                            } // using (SPSite site = new SPSite(siteStr))
                        } // try
                        catch
                        {
                            //CreateLineLog("Error Code User " + LoginName);
                            err = new Exception("Error Code User " + LoginName);
                        }
                    }
                    Count++;
                }
                else // if && OFFICE != "Румянцево"
                {
                }
            } // foreach
            #endregion foreach
            return err;
        }
        #endregion Process Methods
    }
}
